package com.gin.kotlin.vegetables_kot.base

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.os.Build
import androidx.annotation.IntRange
import com.gin.kotlin.vegetables_kot.app.App


/**
 * 剪贴板工具类
 */
class ClipboardUtils {
    companion object {
        /**
         * 获取剪贴板管理器
         * @param context Context
         * @return ClipboardManager
         */
        fun getManager(context: Context = App.INSTANCE) = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager

        /**
         * 获取剪贴板指定位置上的内容
         * @param index Int
         * @param context Context
         * @return String?
         */
        fun getText(@IntRange(from = 0)  index:Int,context: Context = App.INSTANCE) = getManager(context).takeIf { it.hasPrimaryClip() }?.primaryClip?.getItemAt(index)?.text?.toString()

        /**
         * 向剪贴板中写入文本
         * @param text String
         * @param context Context
         */
        fun setText(text:String,context: Context = App.INSTANCE) = getManager(context).setPrimaryClip(ClipData.newPlainText("",text))

        /**
         * 清空剪贴板内容
         * @param context Context
         */
        fun clear(context: Context = App.INSTANCE) = if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.P) getManager(context).clearPrimaryClip() else setText("",context)
    }
}